package br.pucrs.lognplay.service;

import java.util.List;

import javax.ejb.Stateless;

import br.pucrs.lognplay.entity.LogSource;
import br.pucrs.lognplay.repository.LogSourceRepository;
import br.pucrs.lognplay.repository.RepositoryManager;

@Stateless
public class LogSourceManagementServiceBean implements LogSourceManagementService {

	public void mergeLogSource(LogSource logSource) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			LogSourceRepository logSourceRepository = RepositoryManager.getLogSourceRepository();
			logSourceRepository.merge(logSource);
			RepositoryManager.commitTransaction();
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on merge a log source", e);
		}
	}

	public LogSource getLogSourceById(String id) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			LogSourceRepository logSourceRepository = RepositoryManager.getLogSourceRepository();
			LogSource logSource = logSourceRepository.get(id);
			RepositoryManager.commitTransaction();
			return logSource;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on get a log source by id", e);
		}
	}

	public List<LogSource> listAllLogSources() throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			LogSourceRepository logSourceRepository = RepositoryManager.getLogSourceRepository();
			List<LogSource> logSources = logSourceRepository.listAll();
			RepositoryManager.commitTransaction();
			return logSources;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on list all log sources", e);
		}
	}

	public List<LogSource> listLogSourcesByClientId(String clientId) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			LogSourceRepository logSourceRepository = RepositoryManager.getLogSourceRepository();
			List<LogSource> logSources = logSourceRepository.listByClientId(clientId);
			RepositoryManager.commitTransaction();
			return logSources;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on list log sources by client id", e);
		}
	}
}
